package com.jinkaimen.kqb.utils;

import java.io.InputStream;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;

public class StringUtils {
	public static final String EMPTY = "";
	private static String hexStr = "0123456789ABCDEF";
	private static String[] binaryArray = { "0000", "0001", "0010", "0011", "0100", "0101", "0110",
			"0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" };

	/**
	 * 将字符串里面的大写字母转换小写字母
	 * 
	 * @param upper
	 * @return
	 */
	
	public static String upperCaseToLowerCaseS(String upper) {
		String s = "";
		for (int i = 0; i < upper.length(); i++) {
			if (upper.charAt(i) >= 'A' && upper.charAt(i) <= 'Z') {
				s = s + upperCaseToLowerCase(upper.charAt(i));
			} else {
				s = s + upper.charAt(i);
			}
		}
		return s;
	}

	public static char upperCaseToLowerCase(char ch) {
		char vch;
		vch = (char) (ch + 32);
		return vch;
	}

	/**
	 * 16进制转成2进制
	 */

	public static String HexToBinaryString(String str) {// 10
		String str_result = "";
		char[] sss = str.toCharArray();
		for (int i = 0; i < str.length(); i++) {
			for (int j = 0; j < hexStr.length(); j++) {
				if (hexStr.charAt(j) == sss[i]) {
					str_result = str_result + binaryArray[j];
					break;
				}
			}
		}
		return str_result;
	}

	/**
	 * 二进制转成16进制
	 */

	public static String BinaryToHexString(String str) {// 10
		int n = str.length() / 4;// 2
		int m = str.length() % 4;// 2
		String str_result = "";
		if (m != 0) {// 不整除
			for (int j = 0; j < binaryArray.length; j++) {
				if (binaryArray[j].equals(addZero(str.substring(0, m)))) {
					str_result = str_result + hexStr.charAt(j);
					break;
				}
			}
			int start = m;
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < binaryArray.length; j++) {
					if (binaryArray[j].equals(str.substring(start, start + 4))) {
						str_result = str_result + hexStr.charAt(j);
						break;
					}
				}
				start = start + 4;
			}
		} else {// 整除
			int start = 0;
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < binaryArray.length; j++) {
					if (binaryArray[j].equals(str.substring(start, start + 4))) {
						str_result = str_result + hexStr.charAt(j);
						break;
					}
				}
				start = start + 4;
			}
		}
		return str_result;
	}

	/**
	 * 补齐五位数
	 */

	public static String addZero(String str) {
		String s = str;
		for (int i = 0; i < 5 - str.length(); i++) {
			s = "0" + s;
		}
		return s;
	}

	/**
	 * 设置二进制第几位的值 默认从左到右 第一位开始 然后转换为十进制
	 * 
	 * @param str
	 *            十进制数据 先将十进制转化二进制
	 * @param position
	 *            第几位
	 * @param s
	 *            1/0
	 * @return
	 */
	public static String setBinaryPositionString(String str, int position, int s) {
		String binary = Integer.toBinaryString(Integer.parseInt(str));
		if (binary.length() < 5) {// 5位二进制数据
			int index = binary.length();
			for (int i = 0; i < 5 - index; i++) {
				binary = "0" + binary;
			}
		}
		String str_left = binary.substring(0, 5 - position);
		String str_right = binary.substring(5 - position + 1, 5);
		String str_last = str_left + s + str_right;
		BigInteger bb = new BigInteger(str_last, 2);
		return bb.toString();
	}

	/**
	 * 将2进制第position位设置为0/1 s： 1 或0
	 */

	public static String SetBinaryToHexString(String str, int position, int s) {
		if (position > str.length()) {
			str = "0000" + str;
		}
		// str前面0的个数
		int n = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == '0') {
				n++;
			} else {
				break;
			}
		}
		int m = position + n - 1;
		str = str.substring(0, m) + s + str.substring(m + 1, str.length());
		return BinaryToHexString(str);
	}

	/**
	 * 电话号码验证
	 * 
	 * @param phoneNumber
	 *            手机号码
	 * @return
	 */
	public static boolean validatePhoneNumber(String phoneNumber) {
		Pattern pattern = Pattern
				.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
		Matcher m = pattern.matcher(phoneNumber);
		return m.matches();
	}

	/**
	 * 验证输入的身份证号是否符合格式要求
	 * 
	 * @param IDNum
	 *            身份证号
	 * @return 符合国家的格式要求为 true;otherwise,false;
	 */
	public static boolean validateIDcard(String IDNum) {
		// String id_regEx1 =
		// "^([1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|(3[0-1]))\\d{3})|([1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|(3[0-1]))\\d{3}[0-9Xx])$";
		String id_regEx1 = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
		Pattern pattern = Pattern.compile(id_regEx1);
		Matcher m = pattern.matcher(IDNum);
		return m.matches();
	}

	/**
	 * 验证一个字符串是否能解析成整数
	 * 
	 * @param numberStr
	 * @return
	 */
	public static boolean canParseInt(String numberStr) {
		try {
			Integer.parseInt(numberStr);
			return true;
		} catch (NumberFormatException e) {
			return false;
		} catch (NullPointerException e) {
			return false;
		}
	}

	/**
	 * 对流转化成字符串
	 * 
	 * @param is
	 * @return
	 */
	public static String getContentByString(InputStream is) {
		try {
			if (is == null)
				return null;
			byte[] b = new byte[1024];
			int len = -1;
			StringBuilder sb = new StringBuilder();
			while ((len = is.read(b)) != -1) {
				sb.append(new String(b, 0, len));
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 关键字高亮显示
	 * 
	 * @param target
	 *            需要高亮的关键字
	 * @param text
	 *            需要显示的文字
	 * @return spannable 处理完后的结果，记得不要toString()，否则没有效果
	 */
	public static SpannableStringBuilder highlight(String text, String target, int colorvalue) {
		SpannableStringBuilder spannable = new SpannableStringBuilder(text);
		CharacterStyle span = null;
		Pattern p = Pattern.compile(target);
		Matcher m = p.matcher(text);
		while (m.find()) {
			span = new ForegroundColorSpan(colorvalue);// 需要重复！
			spannable.setSpan(span, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		return spannable;
	}
//
//	/**
//	 * 用ImageSpan替换文本
//	 */
//	public static SpannableStringBuilder imageReplaceTxt(Context context, int imgRes,
//			SpannableStringBuilder spannableString, int start, int end,int width,int height) {
//		SpannableStringBuilder ss = new SpannableStringBuilder(spannableString);
//		Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), imgRes);
//		MyImageSpan span = new MyImageSpan(context, imgRes,width,height);
//		ss.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//		return ss;
//	}
	/**
	 * 用ImageSpan替换文本
	 */
//	public static SpannableStringBuilder imageReplaceTxt2(Context context, int imgRes,
//			SpannableStringBuilder spannableString, int start, int end) {
//		SpannableStringBuilder ss = new SpannableStringBuilder(spannableString);
//		MyImageSpan span = new MyImageSpan(context, imgRes,31,16);
//		// 用ImageSpan替换文本
//		ss.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//		return ss;
//	}
	/**
	 * 设置文字背景颜色
	 * 
	 * @param target
	 * @param color
	 * @param start
	 * @param end
	 * @return
	 */
	public static SpannableString setTextBackground(String target, int color, int start, int end) {
		SpannableString spanString = new SpannableString(target);
		BackgroundColorSpan span = new BackgroundColorSpan(color);
		spanString.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		return spanString;
	}

	/**
	 * 设置文字前景颜色
	 * 
	 * @param target
	 * @param color
	 * @param start
	 * @param end
	 * @return
	 */
	public static SpannableString setTextForground(SpannableString target, int color, int start,
			int end) {
		ForegroundColorSpan span = new ForegroundColorSpan(color);
		target.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		return target;
	}

	/**
	 * 判断是否全为数字
	 * 
	 * @param content
	 * @return
	 */
	public static boolean isAllNumber(String content) {
		boolean isAllNumber = true;
		if (isNullOrEmpty(content)) {
			return false;
		}
		for (int i = 0; i < content.length(); i++) {
			if (content.charAt(i) < '0' || content.charAt(i) > '9') {
				isAllNumber = false;
			}
		}
		return isAllNumber;
	}

	/**
	 * 把16进制数字字符串转化成为byte数组
	 * 
	 * @param hex
	 * @return byte[]
	 */
	public static byte[] fromHexString(String hex) {
		if (hex == null || hex.length() < 1)
			return new byte[0];

		int len = hex.length() / 2;
		byte[] result = new byte[len];
		len *= 2;

		for (int index = 0; index < len; index++) {
			String s = hex.substring(index, index + 2);
			int b = Integer.parseInt(s, 16);
			result[index / 2] = (byte) b;
			index++;
		}
		return result;
	}

	public static boolean isNullOrEmpty(String str) {
		return str == null ? true : str.equals(EMPTY);
	}

	public static String trimEnd(String s, char c) {
		String result = s;
		while (result.endsWith(String.valueOf(c))) {
			result = result.substring(0, result.length() - 1);
		}
		return result;

	}

	/**
	 * 格式化一段buffer缓冲区
	 * 

	 * @return
	 */
	public static String formatBuffer(byte[] buffer) {
		if (buffer == null) {
			return "<NULL>";
		} else {
			int len = buffer.length;
			StringBuilder s = new StringBuilder();
			s.append("<");
			s.append(len);
			s.append(":");
			if (len > MAX_BUFFER_OUTPUT)
				len = MAX_BUFFER_OUTPUT;
			for (int i = 0; i < len && i < len; i++) {
				byte b = buffer[i];
				if ((b & 0xf0) != 0) {
					s.append(String.format(" %X", b));
				} else {
					s.append(String.format(" 0%X", b));
				}
			}
			s.append(">");
			return s.toString();
		}
	}

	// / <summary>
	// / 检查前len位是不是全半角
	// / </summary>
	// / <param name="str"></param>
	// / <param name="len"></param>
	// / <returns></returns>
	public static boolean isAllDBC(String str, int len) {
		boolean rt = true;
		for (int i = 0; i < len && i < str.length(); i++)
			if (str.charAt(i) > 0x00FE)
				return false;
		return rt;
	}

	// / <summary>
	// / 是否全半角字串。
	// / </summary>
	// / <param name="str"></param>
	// / <returns></returns>
	public static boolean isAllDBC(String str) {
		boolean rt = true;
		for (int i = 0; i < str.length(); i++)
			if (str.charAt(i) > 0x00FE)
				return false;
		return rt;
	}

	// / <summary>
	// / 一个字符转半角
	// / </summary>
	// / <param name="a"></param>
	// / <returns></returns>
	public static char toDBC(char a) {
		if ((a >= '!' && a <= '~'))
			return a;
		else if ((a >= '！' && a <= '～'))
			return (char) ((a & 0x00ff) + 0x0020);
		else
			return a;
	}

	// /// <summary>
	// /// 一个字串转半角
	// /// </summary>
	// /// <param name="a"></param>
	// /// <returns></returns>
	// public static string ToDBC(string a)
	// {
	// string rtstr = "";
	// for (int i = 0; i < a.Length; i++)
	// rtstr += ToDBC(a[i]);
	// return rtstr;
	// }

	// 修改说明：
	// 考虑到原全半角转换方法内存开销巨大的问题，故将其替换
	// ToDBC(string a)与ToSBC(string a)已被新方法代替，但为方便回滚，故仅注释掉
	// 但不知其关联的ToDBC(char a)和ToSBC(char a)是否被他其他方法依赖，故暂时保留
	// 新方法经开发测试，未发现问题，但实际效果仍需测试人员测试确认

	// / <summary>一个字串转半角</summary>
	// / <param name="input">任意字符串</param>
	// / <returns>半角字符串</returns>
	// /<remarks>
	// /全角空格为12288，半角空格为32
	// /其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
	// /</remarks>
	public static String toDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375)
				c[i] = (char) (c[i] - 65248);
		}
		return new String(c);
	}

	// / <summary>
	// / 一个字符转全角
	// / </summary>
	// / <param name="a"></param>
	// / <returns></returns>
	public static char toSBC(char a) {
		if ((a >= '！' && a <= '～'))
			return a;
		else if ((a >= '!' && a <= '~'))
			return (char) ((a - 0x0020) | 0xff00);
		else
			return a;
	}

	// /// <summary>
	// /// 一个字串转全角
	// /// </summary>
	// /// <param name="a"></param>
	// /// <returns></returns>
	// public static string ToSBC(string a)
	// {
	// string rtstr = "";
	// for (int i = 0; i < a.Length; i++)
	// rtstr += ToSBC(a[i]);
	// return rtstr;
	// }

	// / <summary>
	// / 一个字串转全角
	// / </summary>
	// / <param name="input">任意字符串</param>
	// / <returns>全角字符串</returns>
	// /<remarks>
	// /全角空格为12288，半角空格为32
	// /其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
	// /</remarks>
	public static String toSBC(String input) {
		// 半角转全角：
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 32) {
				c[i] = (char) 12288;
				continue;
			}
			if (c[i] < 127)
				c[i] = (char) (c[i] + 65248);
		}
		return new String(c);
	}

	public static final int MAX_BUFFER_OUTPUT = 1024;

	// / <summary>
	// / 截取字符串，全角长度算2个
	// / </summary>
	// / <param name="source"></param>
	// / <param name="length"></param>
	// / <returns></returns>
	public static String truncateStringWithDBC(String source, int length) {
		int dbcCount = 0;
		for (int i = 0; i < length && i < source.length(); i++) {
			// 全角字符
			if (source.charAt(i) > 0x00FE)
				dbcCount += 2;
			else
				dbcCount += 1;
			if (dbcCount >= length)
				return source.substring(0, i + 1);
		}
		return source;
	}

	public static String[] getNewStrArray(int count) {
		String[] strs = new String[count];
		for (int i = 0; i < count; i++)
			strs[i] = "";
		return strs;
	}

	public static boolean isNum(String str) {
		boolean issid = false;
		Pattern regex = Pattern.compile("^[0-9]*$");// Pattern.compile("^(?<num>[0-9])");//考滤放配置文件
		issid = regex.matcher(str).matches();
		return issid;
	}

	public static int str2int(String str, int def) {
		try {
			if (str.length() == 0)
				return def;
			str = toDBC(str);
			return Integer.parseInt(str);
		} catch (Exception e) {
			e.printStackTrace();
			return def;
		}

	}

	public static long str2int(String str, long def) {

		try {
			if (str.length() == 0)
				return def;
			str = toDBC(str);
			return Long.parseLong(str);
		} catch (Exception e) {
			e.printStackTrace();
			return def;
		}

	}

	// / <summary>
	// / i.tostring().length>length return i.tostring(
	// / </summary>
	// / <param name="i"></param>
	// / <param name="length"></param>
	// / <param name="fillwith"></param>
	// / <returns></returns>
	public static String int2str(int i, int length, String fillwith) {
		String rt = String.valueOf(i);
		if (fillwith.length() == 0)
			return rt;
		if (rt.length() >= length)
			return rt;

		rt = String.format("{" + fillwith + ":D" + length + "}", i);
		return rt;
	}

	public static String substring(String str, int len) {
		if (str.length() <= len)
			return str;
		else
			return str.substring(0, len);
	}

	public static boolean strEquals(String lval, String rval) {
		if (lval == null) {
			return rval == null;
		} else {
			return lval.equals(rval);
		}
	}

	public static String safeTruncate(String str, int len) {
		if (str.length() <= len)
			return str;
		else
			return str.substring(0, len);
	}

	/**
	 * 
	 * @param str1
	 * @param str2
	 * @return 返回true，如果两个字符串相等；否则返回false。
	 */
	public static boolean equal(String str1, String str2) {
		if (str1 == null) {
			return str2 == null;
		} else {
			return str1.equals(str2);
		}
	}

	/**
	 * 验证一个字符串是否能解析成双精度浮点数
	 * 
	 * @param numberStr
	 * @return
	 */
	public static boolean canParseDouble(String numberStr) {
		try {
			Double.parseDouble(numberStr);
			return true;
		} catch (NumberFormatException e) {
			return false;
		} catch (NullPointerException e) {
			return false;
		}
	}

	public static String getMessageId() {
		Calendar sdate = Calendar.getInstance();
		Calendar edate = Calendar.getInstance();
		sdate.setTimeInMillis(1420041600);
		edate.setTimeInMillis(new Date().getTime());
		// System.out.println(edate.getTimeInMillis()-sdate.getTimeInMillis());
		long msgid = edate.getTimeInMillis() - sdate.getTimeInMillis();
		return msgid + "";
	}

	/**
	 *
	 * @return
	 */
	public static boolean validataLegalString4(String content) {
		if (validateLegalString(content)) {
			// 进一步验证字符串是否是0-9、a-z、A-Z，下划线
			for (int i = 0; i < content.length(); i++) {
				if (!isWord(content.charAt(i))) {
					return false;
				}
				if (isChinese(content.charAt(i))) {
					return false;
				}
			}
			if (content.contains("_")) {
				return false;
			}
			return true;
		} else {
			return false;
		}
	}

	public static boolean validataLegalString5(String content) {
		if (validateLegalString(content)) {
			// 进一步验证字符串是否是0-9、a-z、A-Z，下划线 汉字
			for (int i = 0; i < content.length(); i++) {
				if (!isRightChar(content.charAt(i))) {
					return false;
				}
			}
			if (content.contains("_")) {
				return false;
			}
			if (content.contains("1") || content.contains("2") || content.contains("3")
					|| content.contains("4") || content.contains("5") || content.contains("6")
					|| content.contains("7") || content.contains("8") || content.contains("9")
					|| content.contains("0")) {
				return false;
			}
			return true;
		} else {
			return false;
		}
	}

	public static boolean validataLegalString7(String content) {
		if (validateLegalString(content)) {
			// 进一步验证字符串是否是0-9、a-z、A-Z，下划线 汉字
			for (int i = 0; i < content.length(); i++) {
				if (!isRightChar(content.charAt(i))) {
					return false;
				}
			}
			if (content.contains("_")) {
				return false;
			}
			return true;
		} else {
			return false;
		}
	}

	public static boolean validataLegalString6(String content) {
		if (validateLegalString(content)) {
			// 进一步验证字符串是否是0-9、a-z、A-Z，下划线
			for (int i = 0; i < content.length(); i++) {
				if (!isRightChar(content.charAt(i))) {
					return false;
				}
			}
			if (content.contains("_")) {
				return false;
			}
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 验证字符串内容是否合法
	 * 
	 * @param content
	 *            字符串内容
	 * @return
	 */
	public static boolean validateLegalString(String content) {
		String illegal = "`~!#%^&*=+\\|{};:'\",<>/?○●★☆☉♀♂※¤╬の〆，？！@￥$.。()（）";
		boolean legal = true;
		L1: for (int i = 0; i < content.length(); i++) {
			for (int j = 0; j < illegal.length(); j++) {
				if (content.charAt(i) == illegal.charAt(j)) {
					legal = false;
					break L1;
				}
			}
		}
		return legal;
	}

	/**
	 * 验证是否是汉字或者0-9、a-z、A-Z
	 * 
	 * @param c
	 *            被验证的char
	 * @return true代表符合条件
	 */
	public static boolean isRightChar(char c) {
		return isChinese(c) || isWord(c);
	}

	/**
	 * 校验某个字符是否是a-z、A-Z、_、0-9
	 * 
	 * @param c
	 *            被校验的字符
	 * @return true代表符合条件
	 */
	public static boolean isWord(char c) {
		return Pattern.compile("[\\w]").matcher(String.valueOf(c)).matches();
	}

	/**
	 * 判定输入的是否是汉字
	 * 
	 * @param c
	 *            被校验的字符
	 * @return true代表是汉字
	 */
	public static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	// 不能全是相同的数字或者字母（如：000000、111111、aaaaaa） 全部相同返回true
	public static boolean equalStr(String numOrStr) {
		boolean flag = true;
		char str = numOrStr.charAt(0);
		for (int i = 0; i < numOrStr.length(); i++) {
			if (str != numOrStr.charAt(i)) {
				flag = false;
				break;
			}
		}
		return flag;
	}

	/**
	 * 邮箱验证
	 * 
	 * @param mail
	 *            邮箱
	 * @return
	 */
	public static boolean validateEmail(String mail) {
		Pattern pattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
		Matcher m = pattern.matcher(mail);
		return m.matches();
	}

	public static boolean isContainsChinese(String str) {
		String regEx = "[\u4e00-\u9fa5]";
		Pattern pat = Pattern.compile(regEx);
		Matcher matcher = pat.matcher(str);
		boolean flg = false;
		if (matcher.find()) {
			flg = true;
		}
		return flg;
	}
	/**
	 * 判断联成员身份
	 * @param rawIndentity
	 * @return
	 */
	public static String getLianMemberIndentity(String rawIndentity){
		String currentindentity = "";
		String iden = addZero(Integer.toBinaryString(Integer.parseInt(rawIndentity)));
		if (iden.substring(1, 2).equals("1") && iden.substring(2, 3).equals("1")) {
			currentindentity = "4";
		} else if (iden.substring(1, 2).equals("1")) {
			currentindentity = "2";
		} else if (iden.substring(2, 3).equals("1")) {
			currentindentity = "1";
		} else if (iden.substring(0, 1).equals("1")) {
			currentindentity = "3";
		} else if (iden.substring(0, 3).equals("000")) {
			currentindentity = "5";
		}
		return currentindentity;
	}
}
